var amqp = require('amqplib/callback_api');
var log4js = require('log4js');
var logger = log4js.getLogger('AMQConnection');
var instance = null;

function AMQConnection() {
    logger.trace('enter constructor');
    this.conn = null;
}

module.exports = AMQConnection;

AMQConnection.prototype.connect = function(host, port, cb) {
    logger.trace('enter connect');
    var url = 'amqp://' + host + ':' + port;
    var that = this;

    if (this.conn === null) {
        logger.debug('connect to: ' + url);
        amqp.connect(url, null, function(err, conn) {
            if (err !== null) {
                logger.error('cannot connect to: ' + url);
                logger.error(err);
                cb(err);
            } else {
                logger.debug('connected to: ' + url);
                that.conn = conn;
                cb(true);
            }
        });
    } else {
        logger.debug('connection is existed.');
        cb({message: 'connection is existed. please disconnect first and reconnect again.'});
    }
};

AMQConnection.prototype.disconnect = function() {
    logger.trace('enter disconnect');
    if (this.conn !== null) {
        this.conn.close();
        this.conn = null;
    }
};

AMQConnection.getInstance = function() {
    if (instance === null) {
        instance = new AMQConnection();
    }

    return instance;
};
